package com.audaque.springboot.foshanupload.security.valid.rsp.login;

import com.audaque.springboot.foshanupload.security.exception.CaptchaException;
import com.audaque.springboot.foshanupload.core.result.R;
import com.audaque.springboot.foshanupload.core.enums.ResultCodeEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zgb
 * @desc 认证失败处理器
 * @date 2022-08-05 18:00:31
 */
@Slf4j
@Component
public class MyAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;



    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        exception.printStackTrace();
        log.error(exception.getMessage());
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        


        R r = new R<>();
        r.setSuccess(false);
        r.setCode(ResultCodeEnum.LOGIN_FAILE.getCode());
        r.setMsg(ResultCodeEnum.LOGIN_FAILE.getMsg());
        if (exception instanceof LockedException) {
            r.setMsg("账户被锁定，登录失败!");
        } else if (exception instanceof BadCredentialsException) {
            r.setMsg("账户名或密码输入错误，登录失败!");
        } else if (exception instanceof DisabledException) {
            r.setMsg("账户被禁用，登录失败!");
        } else if (exception instanceof AccountExpiredException) {
            r.setMsg("账户已过期，登录失败!");
        } else if (exception instanceof CredentialsExpiredException) {
            r.setMsg("密码已过期，登录失败!");
        } else if(exception instanceof CaptchaException) {
            r.setMsg("验证码失败："+exception.getMessage());
        }else {
            r.setMsg("登录失败!");
        }

        try {
            out.write(objectMapper.writeValueAsString(r));
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }



    }
}
